package plugin_splicing

import (
	"fmt"
	"log"
	. "m7s.live/engine/v4"
	"m7s.live/engine/v4/config"
	"net/http"
	"os/exec"
	"strconv"
	"time"
)

var defaultYaml DefaultYaml

var splicingTaskArray = make(map[string]*SplicingTask)

type SplicingConfig struct {
	DefaultYaml
	config.Publish
	config.Subscribe
	Ffmpeg  string         `default:"ffmpeg" desc:"ffmpeg的路径 "`
	OnStart []StreamConfig `yaml:"onstart"`
}

type StreamConfig struct {
	Resolution string `default:"720*576" yaml:"resolution"`
	VideoCodec string `default:"libx264" yaml:"videocodec"` //libx264, libx265
	Fps        string `default:"25" yaml:"fps"`
}

func (t *SplicingConfig) OnEvent(event any) {
	switch v := event.(type) {
	case IPublisher:
		log.Println("SplicingConfig OnEvent IPublisher...")
	case FirstConfig:
		log.Println("splicing FirstConfig")
		for _, stream := range t.OnStart {
			t.SetUpSplicingTask(stream)
		}
		break
	case config.Config:
		log.Println("splicing config.Config")
		break
	case SEclose:
		log.Println("splicing SEclose:%s", v.Target.Path)
		break
		// case SEpublish:
		// 	log.Println("transform SEpublish:%s", v.Stream.Path)
		// 	break
	}
}

var conf = &SplicingConfig{
	DefaultYaml: defaultYaml,
}

var SplicingPlugin = InstallPlugin(conf)

func (t *SplicingConfig) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	//streamPath := strings.TrimPrefix(r.RequestURI, "/transform/")

	streamConfig := StreamConfig{
		Resolution: "352*288", //CIF 352*288 qcif 176×144 320*240  1280*720
		Fps:        "25",
		VideoCodec: "libx264", //libx264,libx265
	}

	streamPath := r.URL.Query().Get("streampath")
	streamConfig.StreamPath = streamPath

	t.SetUpSplicingTask(streamConfig)

	w.Write([]byte("ok"))
}

func (t *SplicingConfig) SetDefaultStreamConfig(config *StreamConfig) {
	// streamConfig := StreamConfig{
	// 	TransType:     0,
	// 	StreamPath:    "",
	// 	NewStreamPath: "",
	// 	Resolution:    "352*288", //CIF 352*288 qcif 176×144 320*240  1280*720
	// 	Fps:           "25",
	// 	VideoCodec:    "libx264", //libx264,libx265

	// 	HasOsd:       false,
	// 	OsdText:      "M7S 转码",
	// 	OsdFontColor: "green",
	// 	OsdFontsize:  100,
	// 	OsdX:         50,
	// 	OsdY:         50,
	// 	OsdBox:       0,
	// 	OsdBoxcolor:  "yellow",
	// }

	if config.Fps == "" {
		config.Fps = "25"
	}

	if config.Resolution == "" {
		config.Resolution = "352*288"
	}

	if config.VideoCodec == "" {
		config.VideoCodec = "libx264"
	}

}

func (t *SplicingConfig) SetUpTransformTask(config StreamConfig) {
	//更新默认配置
	t.SetDefaultStreamConfig(&config)

	task := &SplicingTask{
		plugin:       t,
		streamConfig: config,
	}

	go task.setupFfmpegTransformThrd0()
	return

}
